package btcdemo.btcdemo.security;

import java.security.MessageDigest;

/**
 * sha256加密工具类
 *
 * @author blues
 */
public class Sha256Utils {

    public static final String KEY_SHA_256 = "SHA-256";

    /**
     * sha256算法
     * @param before
     * @return
     */
    public static String sha256(String before) {
        MessageDigest messageDigest;
        String after = "";
        try {
            messageDigest = MessageDigest.getInstance(KEY_SHA_256);
            messageDigest.update(before.getBytes());
            after = byteArrayToString(messageDigest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return after.toUpperCase();
    }

    /**
     * 下面这个函数用于将字节数组换成成字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteArrayToString(byte[] byteArray) {
        StringBuilder builder = new StringBuilder();
        String temp;
        for (int i = 0; i < byteArray.length; i++) {
            temp = Integer.toHexString(byteArray[i] & 0xFF);
            if (temp.length() == 1) {
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }

}
